{% extends "base.html" %}

{% block title %}SimpleTrade - 最新估值{% endblock %}

{% block extra_css %}
    <style>
        /* 最新估值表格特有样式 */
        .valuation-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin: 20px 0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .valuation-table th {
            background: #3498db;
            color: white;
            font-weight: 600;
            padding: 14px 15px;
            text-align: left;
            position: relative;
            cursor: pointer;
        }

        .valuation-table th:hover {
            background: #2980b9;
        }

        .valuation-table td {
            padding: 14px 15px;
            border-bottom: 1px solid #f0f2f5;
            transition: background 0.2s ease;
        }

        .valuation-table tr:last-child td {
            border-bottom: none;
        }

        .valuation-table tr:hover td {
            background: #f8fafc;
        }

        /* 排序箭头 */
        .sort-arrow {
            display: inline-block;
            margin-left: 5px;
            font-size: 0.8em;
        }

        /* 列宽优化 */
        .valuation-table th:nth-child(1),
        .valuation-table td:nth-child(1) {
            width: 15%;
        }
        .valuation-table th:nth-child(2),
        .valuation-table td:nth-child(2) {
            width: 35%;
        }
        .valuation-table th:nth-child(3),
        .valuation-table td:nth-child(3) {
            width: 20%;
        }
        .valuation-table th:nth-child(4),
        .valuation-table td:nth-child(4) {
            width: 15%;
        }
        .valuation-table th:nth-child(5),
        .valuation-table td:nth-child(5) {
            width: 15%;
        }

        /* 涨幅数值高亮 */
        .growth-positive {
            color: #e74c3c;
            font-weight: 600;
        }
        
        .growth-negative {
            color: #27ae60;
            font-weight: 600;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
            font-size: 1.1em;
        }
        
        /* 按钮样式 */
        .action-btn {
            padding: 8px 15px;
            background: #40BA8D;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s; /* 增加过渡效果 */
        }
        
        .action-btn:hover:not(:disabled) {
            background: #2980b9;
        }
        
        .action-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
        }
        
        /* 消息样式 */
        .result-message {
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: none;
        }
        
        .result-message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .result-message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
{% endblock %}

{% block extra_js %}
    <script>
        // 触发实时估值任务
        function triggerRealtimeValuation() {
            const button = document.getElementById('trigger-realtime-btn');
            const messageDiv = document.getElementById('result-message');
            
            // 禁用按钮并显示加载状态
            button.disabled = true;
            button.textContent = '获取中...';
            messageDiv.style.display = 'none';
            
            // 发送POST请求到API端点
            fetch('/api/trigger-realtime-valuation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    messageDiv.className = 'result-message success';
                    messageDiv.textContent = data.message;
                    // 重新加载页面以显示最新数据
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    messageDiv.className = 'result-message error';
                    messageDiv.textContent = data.error;
                }
                messageDiv.style.display = 'block';
            })
            .catch(error => {
                messageDiv.className = 'result-message error';
                messageDiv.textContent = '请求失败: ' + error.message;
                messageDiv.style.display = 'block';
            })
            .finally(() => {
                // 恢复按钮状态
                button.disabled = false;
                button.textContent = '获取最新估值';
            });
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定按钮点击事件
            const button = document.getElementById('trigger-realtime-btn');
            if (button) {
                button.addEventListener('click', triggerRealtimeValuation);
            }
        });
        function sortTable(columnIndex, dataType) {
            const table = document.querySelector('.valuation-table');
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('tr'));
            const isAscending = table.getAttribute('data-sort-order') === 'asc';
            const newOrder = isAscending ? 'desc' : 'asc';
            
            // 更新排序状态
            table.setAttribute('data-sort-column', columnIndex);
            table.setAttribute('data-sort-order', newOrder);
            
            // 排序
            rows.sort((a, b) => {
                let aValue = a.cells[columnIndex].textContent.trim();
                let bValue = b.cells[columnIndex].textContent.trim();
                
                // 根据数据类型进行比较
                if (dataType === 'number') {
                    // 处理数值排序（包括百分比）
                    aValue = parseFloat(aValue) || 0;
                    bValue = parseFloat(bValue) || 0;
                } else if (dataType === 'date') {
                    // 处理日期排序
                    aValue = new Date(aValue);
                    bValue = new Date(bValue);
                }
                
                if (aValue < bValue) {
                    return newOrder === 'asc' ? -1 : 1;
                }
                if (aValue > bValue) {
                    return newOrder === 'asc' ? 1 : -1;
                }
                return 0;
            });
            
            // 重新插入行
            rows.forEach(row => tbody.appendChild(row));
            
            // 更新表头箭头
            updateSortArrows(columnIndex, newOrder);
        }
        
        function updateSortArrows(sortedColumnIndex, order) {
            // 清除所有箭头
            document.querySelectorAll('.sort-arrow').forEach(arrow => {
                arrow.textContent = '';
            });
            
            // 添加新的箭头
            const arrow = document.querySelector(`th:nth-child(${sortedColumnIndex + 1}) .sort-arrow`);
            if (arrow) {
                arrow.textContent = order === 'asc' ? ' ↑' : ' ↓';
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 为每个表头添加点击事件
            const headers = document.querySelectorAll('.valuation-table th');
            headers.forEach((header, index) => {
                // 添加箭头元素
                const arrow = document.createElement('span');
                arrow.className = 'sort-arrow';
                header.appendChild(arrow);
                
                // 添加点击事件
                header.addEventListener('click', () => {
                    let dataType = 'string';
                    // 根据列索引确定数据类型
                    if (index === 0) {
                        dataType = 'string'; // 基金代码
                    } else if (index === 2) {
                        dataType = 'date'; // 最新日期
                    } else if (index === 3 || index === 4) {
                        dataType = 'number'; // 最新估值和最新涨幅
                    }
                    
                    sortTable(index, dataType);
                });
            });
        });
    </script>
{% endblock %}

{% block content %}
    <h2 class="section-title">最新估值</h2>
    
    <!-- 手动触发按钮 -->
    <button id="trigger-realtime-btn" class="action-btn">获取最新估值</button>
    
    <!-- 结果消息显示区域 -->
    <div id="result-message" class="result-message"></div>

    {% if latest_valuations %}
        <table class="valuation-table" data-sort-column="0" data-sort-order="asc">
            <thead>
                <tr>
                    <th>基金代码</th>
                    <th>基金名称</th>
                    <th>最新日期</th>
                    <th>最新估值</th>
                    <th>最新涨幅(%)</th>
                </tr>
            </thead>
            <tbody>
                {% for item in latest_valuations %}
                <tr>
                    <td>{{ item.fund_code }}</td>
                    <td>{{ item.fund_name }}</td>
                    <td>{{ item.latest_date }}</td>
                    <td>{{ item.latest_value }}</td>
                    <!-- 根据涨幅数值添加不同样式 -->
                    <td class="{{ 'growth-positive' if item.latest_growth|float > 0 else 'growth-negative' if item.latest_growth|float < 0 else '' }}">
                        {{ item.latest_growth }}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <div class="empty-state">
            暂无估值数据<br>
            系统在每个工作日14:55会自动更新基金的最新估值数据
        </div>
    {% endif %}
{% endblock %}